import dashscope
import os

dashscope.api_key = os.getenv("API_KEY")

import dashscope
import requests
import json
import os
from dotenv import load_dotenv, find_dotenv

_ = load_dotenv(find_dotenv())

# 配置API密钥（需替换为实际值）
dashscope.api_key = os.getenv('DASHSCOPE_API_KEY')
BAIDU_MAP_AK = os.getenv('BAIDU_MAP_AK')


# 工具函数：获取地址经纬度
def get_location_coordinates(place):
    url = "http://api.map.baidu.com/geocoding/v3/"
    params = {
        "address": place,
        "output": "json",
        "ak": BAIDU_MAP_AK
    }
    response = requests.get(url, params=params)
    data = response.json()
    if data.get('status') == 0:
        location = data['result']['location']
        return {
            'latitude': location['lat'],
            'longitude': location['lng'],
            'address': place
        }
    return None


# 工具函数：周边POI搜索
def search_nearby_poi(lat, lng, keyword, radius=1000):
    url = "http://api.map.baidu.com/place/v2/search"
    params = {
        "query": keyword,
        "location": f"{lat},{lng}",
        "radius": radius,
        "output": "json",
        "ak": BAIDU_MAP_AK
    }
    response = requests.get(url, params=params)
    data = response.json()
    if data.get('status') == 0:
        return [
            {"name": item["name"], "address": item.get("address", "N/A"), "distance": item.get("distance", 0)}
            for item in data.get("results", [])
        ]
    return []


# 定义工具列表（供大模型调用）
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_location_coordinates",
            "description": "获取指定地点的经纬度坐标",
            "parameters": {
                "type": "object",
                "properties": {
                    "place": {"type": "string", "description": "地点名称，如'北京天安门'"}
                },
                "required": ["place"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_nearby_poi",
            "description": "搜索指定经纬度周边的兴趣点",
            "parameters": {
                "type": "object",
                "properties": {
                    "lat": {"type": "number", "description": "纬度坐标"},
                    "lng": {"type": "number", "description": "经度坐标"},
                    "keyword": {"type": "string", "description": "搜索类型：餐饮/景点/酒店等",
                                "enum": ["餐饮", "景点", "酒店", "超市", "医院", "银行", "娱乐"]},
                    "radius": {"type": "number", "description": "搜索半径(米)，默认1000"}
                },
                "required": ["lat", "lng", "keyword"]
            }
        }
    }
]


# 主处理函数
def process_user_input(user_input):
    # 第一步：意图识别和工具调用
    message = [{
            "role": "user",
            "content": f"分析用户需求并调用工具：{user_input}。需求类型：1)获取经纬度 2)周边搜索"
        }]
    response = dashscope.Generation.call(
        model="qwen-max",
        messages=message,
        tools=tools,
        tool_choice="auto"
    )

    if response.status_code != 200:
        return f"请求失败: {response.code}-{response.message}"

    # 处理工具调用
    tool_calls = response.output.choices[0].message.get("tool_calls", [])
    results =''
    message.append(response.output.choices[0].message)
    if tool_calls:
        results = getFunction(message,response.output.choices[0].message, tool_calls)
    else:
        results = response.output.choices[0].message.content
    # 最终结果生成
    if results:
        return results
    else:
        return "⚠️ 未识别到有效操作，请尝试以下格式：\n" \
               "- '北京天安门的经纬度'\n" \
               "- '西湖附近有什么景点'\n" \
               "- '上海陆家嘴周边美食'"


def getFunction(messages,message, tool_calls):
    call = tool_calls[0]
    func_name = call.get('function').get('name')
    args = json.loads(call.get('function').get('arguments'))
    # messages.append(json.load(message))
    if func_name == "get_location_coordinates":
        coords = get_location_coordinates(args["place"])
        messages.append({
            "role": "tool",
            "name": func_name,
            "content": json.dumps(coords),
            "tool_call_id": call['id']
        })
    elif func_name == "search_nearby_poi":
        pois = search_nearby_poi(args["lat"], args["lng"], args["keyword"])
        messages.append({
            "role": "tool",
            "name": func_name,
            "content": pois,
            "tool_call_id": call['id']
        })

    response = dashscope.Generation.call(
        model="qwen-max",
        messages=messages,
        tools=tools,
        tool_choice="auto",
        tool_calls=tool_calls
    )
    tool_calls = response.output.choices[0].message.get("tool_calls", [])
    results = ''

    if tool_calls:
        messages.append(response.output.choices[0].message)
        results = getFunction(messages, response.output.choices[0].message, tool_calls)
    else:
        results = response.output.choices[0].message.content

    return results

# 测试示例
if __name__ == "__main__":
    print('''
        欢迎使用Map-Demo
        ''')
    # 用户控制台输入并且获取输入信息
    while True:
        user_input = input("请输入数字（1-询问地址，2-结束）：")
        if user_input == '1':
            address = input("请输入地址：")
            print(process_user_input(address))
        elif user_input == '2':
            print("程序已结束。")
            break
        else:
            print("无效输入，请重新输入。")

